/*
 * Copyright (c) 2018. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */
package com.aphaca.rs.web.common;

import com.aphaca.rs.web.util.ResponseWrapper;
import org.jboss.logging.Logger;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@WebFilter(urlPatterns = "/resource/*", filterName = "baseFilter")
public class BaseWebFilter implements Filter {

    private Logger log = Logger.getLogger(this.getClass());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        filterConfig.getFilterName();
        log.info("Filter init()");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ResponseWrapper wrapperResponse = new ResponseWrapper((HttpServletResponse) response);//转换成代理类
        // 这里只拦截返回，直接让请求过去，如果在请求前有处理，可以在这里处理
        chain.doFilter(request, wrapperResponse);
        //将返回值统一转换为json
        wrapperResponse.setHeader("content-type", MediaType.APPLICATION_JSON_UTF8.toString());
        byte[] content = wrapperResponse.getContent();//获取返回值
        //判断是否有值
        if (content.length > 0) {
            String str = new String(content, "UTF-8");
            //把返回值输出到客户端
            ServletOutputStream out = response.getOutputStream();
            out.write(str.getBytes());
            out.flush();
        }
    }

    @Override
    public void destroy() {
        log.info("Filter destroy()");
    }
}
